from datetime import datetime
from peewee import BooleanField, Model, AutoField, CharField, DateTimeField, IntegerField, TextField, FloatField, MySQLDatabase
from config.config import Config

# 数据库配置
db = MySQLDatabase(
    Config.DB_NAME,
    user=Config.DB_USER,
    password=Config.DB_PASSWORD,
    host=Config.DB_HOST,
    port=Config.DB_PORT,
    charset='utf8mb4'
)

class BaseModel(Model):
    class Meta:
        database = db

class ChatSessions(BaseModel):
    id = AutoField()  # 对应 AUTO_INCREMENT
    is_deleted = BooleanField(default=False, column_name='isDeleted')  # tinyint(1) 转换为 Boolean
    session_id = CharField(max_length=100, unique=True)  # UNIQUE KEY 约束
    title = CharField(max_length=20, null=True)  # 允许 NULL
    created_at = DateTimeField(default=datetime.now)  # 自动设置创建时间
    updated_at = DateTimeField(default=datetime.now)  # 需手动更新
    message_count = IntegerField(default=0)
    deleted_at = DateTimeField(null=True)

    class Meta:
        table_name = 'chat_sessions'

class DetailedConversations(BaseModel):
    id = AutoField()
    is_deleted = BooleanField(default=False, column_name='isDeleted')
    conversation_id = CharField(max_length=100, unique=True)
    session_id = CharField(max_length=100)
    user_input = TextField()
    final_prompt = TextField()
    llm_response = TextField()
    final_response = TextField()
    retrieved_documents = TextField(null=True)
    prompt_template = TextField(null=True)
    model_name = CharField(max_length=10, null=True)
    processing_time = FloatField(null=True)
    created_at = DateTimeField(default=datetime.now)
    deleted_at = DateTimeField(null=True)

    class Meta:
        table_name = 'detailed_conversations'

# 创建表（如果不存在）
if __name__ == '__main__':
    db.connect()
    db.create_tables([ChatSessions, DetailedConversations], safe=True)
    db.close()